package com.dld.protocol.image;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.util.Log;

public class DbCache extends SQLiteOpenHelper {

	public static DbCache instance;

	public static DbCache getInstance(Context context) {
		if (instance == null) {
			instance = new DbCache(context, "cache_image.db", null, 1);
		}
		return instance;
	}

	public DbCache(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		db
				.execSQL("create table cachefile(id integer primary key autoincrement,cacheurl text)");
	}

	public synchronized boolean isCached(String url) {
		if (url ==null || "".equals(url)) {
			return false;
		}
		SQLiteDatabase rd = getReadableDatabase();
		Cursor c = rd.rawQuery("select * from cachefile where cacheurl = ?",
				new String[] { url });
		int count = c.getCount();
		c.close();
		return count > 0 ? true : false;
	}

	public synchronized void cacheFile(String url) {
		SQLiteDatabase db = getWritableDatabase();
		ContentValues cv = new ContentValues();
		cv.put("cacheurl", url);
		db.insert("cachefile", null, cv);
	}

	public synchronized void delCacheFile(String url) {
		SQLiteDatabase db = getWritableDatabase();
		db.execSQL("delete from cachefile where cacheurl =?",
				new String[] { url });

	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub

	}

}
